<?php

/**
 *
 * @author ben <ben@spicatech.cn>  Created on 2015-11-2 
 */
class CommisionService {

    protected $comId;

    public function __construct($comId) {
        $this->comId = $comId;
    }

    /**
     * 
     * @param type $orderNo
     * @return type
     */
    public function getUserCommisionFromOrder($orderNo) {
        $c = new CDbCriteria();
        $c->addColumnCondition([
            'com_id' => $this->comId,
            'order_no' => $orderNo,
            'place_id' => 0,
            'status' => 1
        ]);
        $c->addCondition('user_id > 0');
        $model = CommisionUser::model();
        $list = $model
                ->getDbConnection()->createCommand()
                ->select('user_id, ifnull(sum(commission), 0) as amount')
                ->from($model->tableName())
                ->where($c->condition, $c->params)
                ->group('user_id')
                ->queryAll();

        return $list;
    }

    /**
     * 
     * @param type $orderNos
     * @return type
     */
    public function getUserCommisionFromOrders(array $orderNos) {
        $c = new CDbCriteria();
        $c->addColumnCondition([
            'com_id' => $this->comId
        ]);
        $c->addInCondition('order_no', $orderNos);
        $c->addColumnCondition([
            'place_id' => 0,
            'status' => 1
        ]);
        $c->addCondition('user_id > 0');
        $model = CommisionUser::model();
        $list = $model
                ->getDbConnection()->createCommand()
                ->select('user_id, order_no,ifnull(sum(commission), 0) as amount')
                ->from($model->tableName())
                ->where($c->condition, $c->params)
                ->group('user_id, order_no')
                ->queryAll();

        $res = [];
        foreach ($orderNos as $no) {
            if(!isset($res[$no])) {
                $res[$no] = [];
            }
        }
        foreach($list as $k=>$v) {
            $res[$v['order_no']][] = $v;
        }
        return $res;
    }

}
